package zd.cornermemory.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import greendao.RememberCjDao;
import zd.cornermemory.R;
import zd.cornermemory.adapter.RememberCjAdapter;
import zd.cornermemory.adapter.TextAdapter;
import zd.cornermemory.db.GreenDaoManager;
import zd.cornermemory.db.RememberCj;
import zd.cornermemory.utils.Statistics;

import static zd.cornermemory.utils.Statistics.timeToString;

public class RemeberCjActivity extends BaseActivity implements View.OnClickListener{
    private RememberCjAdapter cjAdapter;
    private ListView          listview;
    private List<RememberCj>  cjs;
    private TextView          zpj;
    private TextView          zpj_show;
    private TextView          min_text;
    private TextView          remember_min_text;
    private Button            txt_sesname;
    private TextView          group_text;
    private RememberCjDao     cjDao;
    private RelativeLayout    max_layout,min_layout;
    private PopupWindow popupWindow;
    private int dip;
    private RememberCj minCj, rememberMinCj;
    private View popView;
    private int type;//0 角  1棱 2全读
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remember_cj);
        cjDao =  GreenDaoManager.getInstance().getNewSession().getRememberCjDao();
        initViews();
        initData(true);
        setBackImage();
    }

    private void initData(boolean isFirst) {
        if (isFirst) {
            currentPos = getIntent().getExtras().getInt("currentPos");
            type = getIntent().getExtras().getInt("type",0);
            DisplayMetrics dm = getResources().getDisplayMetrics();
            dip = (int) Math.round(dm.density * 200);
        }

        int po = 0;
        int arrayRes = 0;
        if (type == 0) {
            switch (currentPos) {
                case -1:
                    po = 0;
                    break;
                case 3:
                    po = 1;
                    break;
                case 4:
                    po = 2;
                    break;
                case 5:
                    po = 3;
                    break;
                case -2:
                    po = 4;
                    break;
            }
            arrayRes = R.array.remember;
        } else if (type == 1) {
            switch (currentPos) {
                case 0:
                    po = 0;
                    break;
                case 1:
                    po = 1;
                    break;
                case 2:
                    po = 2;
                    break;
                case 3:
                    po = 3;
                    break;
                case -2:
                    po = 4;
                    break;
            }
//            po = currentPos;
            arrayRes = R.array.remember_edge;
        } else {
            po = currentPos;
            arrayRes = R.array.remember_all;
        }

        String[] scr = getResources().getStringArray(arrayRes);
        if (type == 0) {
            group_text.setText(scr[po]+getString(R.string.corner_d));
        } else if (type == 1) {
            group_text.setText(scr[po] + getString(R.string.edge_d));
        } else {
            group_text.setText(getString(R.string.all_d));
        }
        cjDao.detachAll();
        cjs = cjDao.queryBuilder().where(RememberCjDao.Properties.Group.eq(currentPos),RememberCjDao.Properties.Type.eq(type)).orderDesc(RememberCjDao.Properties.Date).list();
        if (cjs == null) {
            cjs = new ArrayList<>();
        }
        cjAdapter = new RememberCjAdapter(mContext, cjs);
        listview.setAdapter(cjAdapter);
        setMinMax();
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showTimeCj(cjs.get(i));
            }
        });
    }

    private void initViews() {
        listview = findViewById(R.id.listview);
        group_text = findViewById(R.id.group_text);
        zpj = findViewById(R.id.zpj);
        zpj_show = findViewById(R.id.zpj_show);
        txt_sesname = findViewById(R.id.txt_sesname);
        min_text = findViewById(R.id.min);
        remember_min_text = findViewById(R.id.remember_min_text);
        min_layout = findViewById(R.id.min_layout);
        max_layout = findViewById(R.id.max_layout);
        min_layout.setOnClickListener(this);
        max_layout.setOnClickListener(this);
        txt_sesname.setOnClickListener(this);
    }

    private void setMinMax() {
        List<RememberCj> cjList = new ArrayList<>();
        for (RememberCj rememberCj : cjs) {
            if (rememberCj.getStatus() != 2) {
                cjList.add(rememberCj);
            }
        }
        zpj.setText(getString(R.string.avg_all)+getString(R.string.left_k)+cjList.size()+"/"+cjs.size()+getString(R.string.right_k));
        long avg = 0;
        long rememberCount = 0;
        long opCount = 0;
        for (RememberCj cj : cjList) {
            avg += cj.getSingTime();
            rememberCount+=cj.getRememberTime();
            int op = cj.getSingTime()-cj.getRememberTime();
            opCount += op;
        }
        if (avg == 0) {
            zpj_show.setText("N/A");
            min_text.setText("N/A");
            remember_min_text.setText("N/A");
            minCj = null;
            rememberMinCj = null;
        }else{
            String avgStr = getAvg(cjList, avg);
            String rememberAvg = getAvg(cjList, rememberCount);
            String opCountAvg = getAvg(cjList, opCount);

            zpj_show.setText(avgStr+"  ( "+rememberAvg+" + "+opCountAvg+" )");

            minCj = Collections.min(cjList);
            min_text.setText(codeStr(minCj));
            List<Integer> remember = new ArrayList<>();
            for (RememberCj rememberCj : cjList) {
                remember.add(rememberCj.getRememberTime());
            }
            rememberMinCj = null;
            int minRemeber = Collections.min(remember);
            for (RememberCj rememberCj : cjList) {
                if (rememberCj.getRememberTime() == minRemeber) {
                    rememberMinCj = rememberCj;
                    break;
                }
            }

            remember_min_text.setText(Statistics.timeToString(rememberMinCj.getRememberTime()));
        }

    }

    private String getAvg(List<RememberCj> cjList, long avg) {
        double a = avg/cjList.size();
        avg = Math.round(a);
        return timeToString((int) avg);
    }

    private String codeStr(RememberCj cj) {
        String result = "";
        if (cj == null) {
            return result;
        }
        int singTime = cj.getSingTime();
        int rememberTime = cj.getRememberTime();
        int oppre = singTime-rememberTime;
        String singTimeStr = Statistics.timeToString(singTime);
        String rememberTimeStr = Statistics.timeToString(rememberTime);
        String oppreStr = Statistics.timeToString(oppre);

        result += singTimeStr + "  ( " + rememberTimeStr + " + " + oppreStr + " )";
        return result;
    }

    private void showTimeCj(final RememberCj cj) {
        String timeStr = "";
        int mRememberTime = cj.getRememberTime();
        String rememberStr = Statistics.timeToString(mRememberTime);

        int time = cj.getSingTime();

        int opre = time-mRememberTime;//操作时间
        String opreStr = Statistics.timeToString(opre);

        int error = cj.getErrorTime();//罚时
        String errorStr = Statistics.timeToString(error);

        int showTime = time+error;
        String showTimeStr = Statistics.timeToString(showTime);

        timeStr+=showTimeStr;
        if (error != 0) {
            timeStr = "DNF";
        }
        timeStr+="  ( "+rememberStr+" + "+opreStr;

        if (error != 0) {
            timeStr+= " + "+errorStr+" )";
        }else {
            timeStr+=" )";
        }
        String dateStr = Statistics.handleLongDate(cj.getDate(),0);

        String message = "";
        if (type == 2) {
            String edgeStr = showCode(Pro(cj.getEdgeCode()));
            String cornerStr = showCode(Pro(cj.getCode()));
            message = (getString(R.string.edge_code) + edgeStr + "\n" + getString(R.string.corner_code) + cornerStr);
        } else {
            scr = cj.getCode();
            String[] code = Pro(scr);
            scr = showCode(code);
            message = (getString(R.string.bm_)+scr);
        }

        new AlertDialog.Builder(mContext)
                .setTitle(getString(R.string.time) + timeStr)
                .setMessage(message+"\n"+"("+dateStr+")")
                .setCancelable(true)
                .setNegativeButton(getString(R.string.delete), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        cjDao.delete(cj);
                        cjs.remove(cj);
                        cjAdapter.notifyDataSetChanged();
                        setMinMax();
                    }
                })
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private String scr;

private ListView popListView;
private int currentPos;
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.min_layout:
                if (minCj == null) {
                    return;
                }
                showTimeCj(minCj);
                break;
            case R.id.max_layout:
                if (rememberMinCj == null) {
                    return;
                }
                showTimeCj(rememberMinCj);
                break;
            case R.id.txt_sesname:

                int resId = R.layout.pop_window;
                popView = LayoutInflater.from(mContext).inflate(resId, null);
                popListView = (ListView) popView.findViewById(R.id.list);
                int arrayRes = 0;
                int po = 0;
                if (type == 0) {
                    switch (currentPos) {
                        case -1:
                            po = 0;
                            break;
                        case 3:
                            po = 1;
                            break;
                        case 4:
                            po = 2;
                            break;
                        case 5:
                            po = 3;
                            break;
                    }
                    arrayRes = R.array.remember;
                } else if (type == 1) {
                    po = currentPos;
                    arrayRes = R.array.remember_edge;
                } else {
                    po = currentPos;
                    arrayRes = R.array.remember_all;
                }
                String[] scr = getResources().getStringArray(arrayRes);
                TextAdapter scrAdapter = new TextAdapter(mContext, scr, po);
                popListView.setAdapter(scrAdapter);
                popListView.setSelection(po);
                popListView.setOnItemClickListener(listener);

                popupWindow = new PopupWindow(popView, dip, dip+80, true);
                popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.choosearea_bg_mid));
                popupWindow.setTouchable(true);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        darkenBackground(1f);
                    }
                });
                popupWindow.showAsDropDown(view, (txt_sesname.getWidth()-popupWindow.getWidth())/2, 0);
                darkenBackground(0.5f);
                break;
        }
    }

    private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            if (type == 0) {
                switch (i) {
                    case 0 :
                        currentPos = -1;
                        break;
                    case 1 :
                        currentPos = 3;
                        break;
                    case 2 :
                        currentPos = 4;
                        break;
                    case 3 :
                        currentPos = 5;
                        break;
                }
            }else{
                currentPos = i;
            }

            initData(false);
            popupWindow.dismiss();
        }
    };

    private String showCode(String[] str){
        String result = "";
        for(int i=0;i<str.length;i++){
            result += str[i];
            result += " ";
        }
        return result;
    }

    private String[] Pro(String number){
        String[] str;
        int length = number.length();
        int group = length/2;
        if(0==length % 2)
        {
            str=new String[group];
        }
        else
        {
            str= new String[group+1];
        }
        for(int i=0,j=0;i<group;i++,j+=2)
        {
            str[i]=number.substring(j, j+2);
            if(i==(group-1))
            {
                if(1 == length % 2)
                {
                    str[i+1] = number.substring(length-1,length);
                }
            }
        }
        return str;
    }

}
